#include "Common.h"
#include "Renderer.h"

#include "App/AppBase.h"
#include "Utils/Camera.h"
#include "Utils/Timer.h"
#include "Graphics/Texture.h"
#include "Graphics/CGShaderProgram.h"

using namespace RayFrame;

DLL_DECLARE Renderer *RayFrame::g_renderer = NULL;

int Renderer::GetFormatSize(const AttributeFormat format) const {
  static int formatSize[] = { sizeof(float), sizeof(half), sizeof(ubyte) };
  return formatSize[format];
}

Renderer::Renderer(){
  m_clearColor = Color(0.5, 0.5, 1.0, 1.0);

  currentVertexFormat = VF_NONE;
  for (unsigned i = 0; i < MAX_VERTEXSTREAM; i++){
    currentVertexBuffers[i] = VB_NONE;
    currentOffsets[i] = 0;
  }
  currentIndexBuffer = IB_NONE;

  m_defaultFont = NULL;
  g_renderer = this;
}

Renderer::~Renderer()
{

}

void Renderer::ExitAPI()
{
  // delete objects created by factory method
  Depot::InstanceRef().RemoveDepotBucket( CameraBucket::Instance() );
  Depot::InstanceRef().RemoveDepotBucket( TextureBucket::Instance() );
  Depot::InstanceRef().RemoveDepotBucket( RenderTargetBucket::Instance() );
}

void RayFrame::Renderer::RenderDebugInfo( double timeElapsed )
{
  char debugBuf[BUFFER_LENGTH];

  glm::vec3 cameraPos = g_App->GetCamera()->GetEye();
  glm::vec3 centerPos = g_App->GetCamera()->GetCenter();
  sprintf(debugBuf, "Camera pos: (%4.2f, %4.2f, %4.2f), looking at: (%4.2f, %4.2f, %4.2f)\n, FPS: %4.2f",
          cameraPos.x, cameraPos.y, cameraPos.z, centerPos.x, centerPos.y,
          centerPos.z, FrameTimer::InstanceRef().GetFPS());

  this->RenderText(0, 0, debugBuf);
}

CGShaderProgram* RayFrame::Renderer::CreateCGShaderProgram()
{
  CGShaderProgram* sm = new CGShaderProgram();
  InsertShaderProgram(EMPTY_STRING, sm);
  return sm;
}
